package cn.jiangjiesheng.bootstrap.fileport.domain.doc;

import com.google.common.io.Resources;
import com.lowagie.text.Font;
import com.lowagie.text.pdf.BaseFont;
import fr.opensagres.poi.xwpf.converter.pdf.PdfOptions;
import lombok.extern.slf4j.Slf4j;
import lombok.var;
import org.apache.poi.xwpf.usermodel.XWPFDocument;

import java.io.*;

/**
 * 生成PDF文件
 * <p>
 * Created by dev@jiangjiesheng.cn on 2021/3/16  <br/>
 * @author jerrylau
 */
@Slf4j
public class PdfConverterDo {

    private final ByteArrayOutputStream out = new ByteArrayOutputStream();

    public PdfConverterDo(byte[] bytes) throws IOException {
        System.out.println("文件长度：" + bytes.length);
        process(new ByteArrayInputStream(bytes));
    }

    /**
     * word转为PDF
     *
     * @param is 输入文件流
     */
    public PdfConverterDo(InputStream is)  {
        try {
            this.process(is);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void process(InputStream is) throws IOException {
        PdfOptions options = PdfOptions.create();
        options.fontProvider((familyName, encoding, size, style, color) -> {
            try {
                var font = Resources.getResource("templates/static/song.ttf");
                BaseFont bfChinese = BaseFont.createFont(font.toString(),
                        encoding,
                        BaseFont.NOT_EMBEDDED
                );
                Font fontChinese = new Font(bfChinese, size, style, color);
                if (familyName != null) {
                    fontChinese.setFamily(familyName);
                }
                return fontChinese;
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }
        });
        // 1) Load DOCX into XWPFDocument
        XWPFDocument document = new XWPFDocument(is);
        fr.opensagres.poi.xwpf.converter.pdf.PdfConverter.getInstance().convert(document, out, options);
        // 2) Prepare Pdf options
        // 3) Convert XWPFDocument to Pdf
        out.close();
    }

    public OutputStream toOutputStream() {
        return out;
    }

    /**
     * 转为二进制
     *
     * @return
     */
    public byte[] toBytes() {
        return out.toByteArray();
    }
}
